package com.bitcointoolkit.web.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bitcointoolkit.web.security.CSRFTokenManager;
import com.bitcointoolkit.web.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Predicate;
import com.google.common.collect.Maps;

/**
 * 预处理拦截器 主要用于加入一些视图层需要的公共功能和数据支持
 * 
 * @author caisirius
 */
public class PretreatmentInterceptor extends BaseInterceptor {
	
	@Value("${view.debug}")
	private boolean debug;

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (isNotFilter(request)) {
			return;
		}
		
		// GET请求进入某个页面时
		if (!HttpUtils.isAjax(request) && HttpUtils.isGet(request)) {
			if(modelAndView==null){
				return ;
			}
			String path = request.getRequestURI();
			String lastName = WebUtils.extractFilenameFromUrlPath(path);
			modelAndView.addObject("baseURI", path.replace(lastName, "list"));
			modelAndView.addObject("CSRFToken", CSRFTokenManager.getTokenForSession(request.getSession()));
			
			Map<String,Object> modelMap = modelAndView.getModel();
			
			if(debug){
				//利用JSON序列化实现深度COPY
				String json = JSON.toJSONString(modelMap);
				@SuppressWarnings("unchecked")
				Map<String,Object> cloneMap = JSON.parseObject(json, HashMap.class);
				
				//移除Spring自带的key model数据
				Map<String,Object> filteredMap = Maps.filterKeys(cloneMap, new Predicate<String>(){
					@Override
					public boolean apply(String input) {
						return !input.startsWith("org.springframework");
					}
				});
				
				//DEBUG modal object
				modelAndView.addObject("debug", JSON.toJSONString(filteredMap, true));
			}
		}
	}

}
